import { Schema } from 'mongoose';
import { ITaskSession } from '../types/ITaskSession';
import { SubTaskSchema } from './SubTaskSchema';

export const TaskSessionSchema = new Schema<ITaskSession>({
  sessionId: { type: String, required: true, unique: true, index: true },
  userId: { type: String, required: true, index: true },
  title: { type: String, required: true, maxlength: 200 },
  description: { type: String, maxlength: 1000 },
  status: {
    type: String,
    enum: ['active', 'completed', 'paused', 'archived'],
    default: 'active',
    index: true
  },
  priority: {
    type: String,
    enum: ['low', 'medium', 'high', 'urgent'],
    default: 'medium',
    index: true
  },
  tags: [{ type: String, index: true }],
  // 子任务数组
  subTasks: [SubTaskSchema],
  // 整体进度
  overallProgress: { type: Number, min: 0, max: 100, default: 0 },
  metadata: {
    createdBy: { type: String, required: true },
    lastModifiedBy: { type: String, required: true },
    estimatedDuration: { type: Number, min: 0 },
    actualDuration: { type: Number, min: 0 },
    complexity: {
      type: String,
      enum: ['simple', 'medium', 'complex'],
      default: 'medium'
    },
    // 子任务统计信息
    subTaskStats: {
      total: { type: Number, default: 0, min: 0 },
      completed: { type: Number, default: 0, min: 0 },
      inProgress: { type: Number, default: 0, min: 0 },
      pending: { type: Number, default: 0, min: 0 },
      cancelled: { type: Number, default: 0, min: 0 }
    }
  },
  messageCount: { type: Number, default: 0, min: 0 },
  lastMessageAt: { type: Date, index: true },
  completedAt: { type: Date, sparse: true }
}, {
  timestamps: true,
  collection: 'task_sessions'
});

// Compound Indexes
TaskSessionSchema.index({ userId: 1, status: 1 });
TaskSessionSchema.index({ userId: 1, createdAt: -1 });
TaskSessionSchema.index({ status: 1, priority: 1, createdAt: -1 });
TaskSessionSchema.index({ 'metadata.complexity': 1, status: 1 });
TaskSessionSchema.index({ 'subTasks.subTaskId': 1 }, { sparse: true });
TaskSessionSchema.index({ 'subTasks.status': 1 }, { sparse: true });
TaskSessionSchema.index({ 'subTasks.assignedTo': 1 }, { sparse: true });
TaskSessionSchema.index({ 'subTasks.dueDate': 1 }, { sparse: true });
